package com.example.myapplication2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.example.myapplication2.db.TaskDao;
import com.example.myapplication2.model.Task;
import com.example.myapplication2.adapter.TaskAdapter;
import java.util.ArrayList;
import java.util.List;

public class TodoListActivity extends AppCompatActivity {
    private RecyclerView rvTasks;
    private TaskAdapter taskAdapter;
    private TaskDao taskDao;
    private long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_todo_list);

        // 获取当前用户ID
        SharedPreferences prefs = getSharedPreferences("user_info", MODE_PRIVATE);
        currentUserId = prefs.getLong("user_id", -1);

        if (currentUserId <= 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }

        taskDao = new TaskDao(this);
        initViews();
        loadTodayTasks();
    }

    private void initViews() {
        rvTasks = findViewById(R.id.rv_tasks);
        rvTasks.setLayoutManager(new LinearLayoutManager(this));
        
        taskAdapter = new TaskAdapter(this, new ArrayList<>());
        taskAdapter.setOnTaskCompletedListener((task, isCompleted) -> {
            // 更新任务状态
            if (taskDao.updateTaskStatus(task.getId(), isCompleted)) {
                task.setCompleted(isCompleted);
            }
        });
        
        rvTasks.setAdapter(taskAdapter);

        // 添加新任务按钮
        findViewById(R.id.fab_add).setOnClickListener(v -> {
            startActivity(new Intent(this, TaskDetailActivity.class));
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadTodayTasks();
    }

    private void loadTodayTasks() {
        List<Task> tasks = taskDao.getTodayTasks(currentUserId);
        taskAdapter.updateTasks(tasks);
    }
} 